package com.woniuxy.consumer;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.entity.KillBook;
import com.woniuxy.util.RabbitmqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author ：CuiYC
 * @description：
 * @date ：Created in 2025/3/20 19:14
 * @modified By：
 */
@Component
public class AddKillRedisConsumer {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(queues = RabbitmqConst.SHOW_KILL_BOOK_QUEUE)
    public void receive(String msg, Channel channel, Message message) {
        try {
            /**
             * 添加秒杀商品信息到redis中
             */
//            List<KillBook> killBooks = JSON.parseArray(msg, KillBook.class);
//            for (KillBook killBook : killBooks) {
//                redisTemplate.opsForHash().put("SECKILLSERVICEIMPL:ADDKILLBOOK",killBook.getBookId()+"",killBook);
//            }
            KillBook killBook = JSON.parseObject(msg, KillBook.class);
            redisTemplate.opsForHash().put("SECKILLSERVICEIMPL:ADDKILLBOOK",killBook.getBookId()+"",killBook);
            System.out.println("秒杀商品信息已添加到redis");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
